package com.webserver.core;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.controller.ArticleController;
import com.webserver.controller.ToolsController;
import com.webserver.controller.UserController;
import com.webserver.core.ClientHandler;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static File rootDir,staticDir;

    static {
        try {
            rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        staticDir = new File(rootDir,"static");
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        String path = request.getRequestURI();

        //根据请求路径判断是否为处理某个业务

        File dir = new File(rootDir,"/com/webserver/controller");
        File[] files = dir.listFiles(f->f.getName().endsWith(".class"));
        for (File f : files){
            String fileName = f.getName();
            String className = fileName.split("\\.")[0];
            Class c = Class.forName("com.webserver.controller."+className);
            if(c.isAnnotationPresent(Controller.class)){//判断是否是注释方法
                Method[] methods = c.getMethods();
                for (Method m : methods){
                    if(m.isAnnotationPresent(RequestMapping.class)){//判断是否是注释方法
                        RequestMapping rm = m.getAnnotation(RequestMapping.class);
                        String value = rm.value();
                        if(value.equals(path)){
                            Object controller = c.newInstance();
                            m.invoke(controller,request,response);
                            return;
                        }
                    }
                }
            }
        }
        File file = new File(staticDir,path);
        System.out.println("资源是否存在："+file.exists());
        if(!file.isFile()){
            file = new File(staticDir,"root/404.html");
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
        }
        response.setContentFile(file);
    }

}
